package com.sh4.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.codehaus.plexus.util.StringUtils;
import org.springframework.stereotype.Repository;

import com.sh4.dao.XgfsBookDao;
import com.sh4.entity.XgfsBook;

import net.sf.json.JSONObject;

@Repository
public class XgfsBookDaoImpl extends BaseDaoImpl<XgfsBook> implements XgfsBookDao{

	@Override
	public List<Map<String, Object>> list(int pageSize, int pageNo, JSONObject params) {
		
		
		List<String> values = new ArrayList<String>();
		
		String sql = "SELECT  xb.ID_ as id, "
				+ "xb.BOOK_MOBILE_ as bookMobile , "
				+ "xb.OPEN_ID_ as openId , "
				+ "xb.BOOK_ADDRESS_ as bookAddress, "
				+ "xb.BOOK_TYPE_ as bookType , "
				+ "xb.BOOK_STATUS_ as bookStatus, "
				+ "xb.BOOK_AREA_ as bookArea , "
				+ "xb.REMARK_ as remark,"
				+ "xb.CREATE_DATE_ as createDate ,"
				+ "(select GROUP_CONCAT(e.ENUM_NAME_) as bookType from system_enum e where FIND_IN_SET(e.ENUM_CODE_,xb.BOOK_TYPE_) GROUP BY e.PARENT_CODE_) as bookTypeDesc,"
//				+ "s.ENUM_NAME_ as bookTypeDesc, " 
				+ "ss.ENUM_NAME_ as bookStatusDesc"
				+ " FROM xgfs_book xb "
				+ " LEFT JOIN system_enum s ON(s.PARENT_CODE_ = 'xgfs09' and s.ENUM_CODE_ = xb.BOOK_TYPE_) "
				+ "	LEFT JOIN system_enum ss ON(ss.PARENT_CODE_ = 'xgfs10' and ss.ENUM_CODE_ = xb.BOOK_STATUS_)"
				+ " where 1=1 ";
		
		if(params.containsKey("bookMobile") && StringUtils.isNotEmpty(params.getString("bookMobile"))) {
			
			String bookMobile = params.getString("bookMobile");
			sql += " and xb.BOOK_MOBILE_ like ?";
			values.add("%"+bookMobile+"%");
		}
		if(params.containsKey("bookType") && StringUtils.isNotEmpty(params.getString("bookType"))) {
			String bookType = params.getString("bookType");
			sql += " and xb.BOOK_TYPE_ = ?";
			values.add(bookType);
		}
		
		if(params.containsKey("bookStatus") && StringUtils.isNotEmpty(params.getString("bookStatus"))) {
			String bookStatus = params.getString("bookStatus");
			sql += " and xb.BOOK_STATUS_ = ?";
			values.add(bookStatus);
		}
		
		if(params.containsKey("openId") && StringUtils.isNotEmpty(params.getString("openId"))) {
			sql += " and xb.OPEN_ID_ = ?";
			values.add(params.getString("openId"));
		}
		
		sql += " order by xb.CREATE_DATE_ desc";
		
		return this.getArrayPageBySql(pageNo, pageSize, sql , values.toArray(new String [] {}));
	}

	@Override
	public XgfsBook getXgfsBookById(String id) {
		
		String hql = "from XgfsBook a where a.id = ? and a.type = ?";
		
		return this.getByHql(hql, id);
	}


	@Override
	public int countXgfsBook(JSONObject params) {
		
		String sql = "";
		
		sql = "SELECT count(0) as total "
				+ "from xgfs_book where BOOK_STATUS_ = ?";
		
		BigInteger count = (BigInteger)this.getUniqueResultBySql(sql,params.getString("bookStatus")).get("total");
		
		return count.intValue();
	}

}
